package com.imdroid.carac.activities;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;

public class RecordMenuActivity extends Activity {
	/**
	 * The string of the tag.
	 */
	private String TAG = "RecordMenuActivity";
	/**
	 * The grid view of the video.
	 */
	private ListView list;
	private ArrayList<HashMap<String, Object>> data;
	private Handler handler;
	/**
	 * The grid data adapter
	 */
	private VideoAdapter sa;
	/**
	 * the thread of timer
	 */
	private TimeRunner timeRunner = null;
	/**
	 * The button of the count down.
	 */
	private Button stateButton;
	/**
	 * The wake lock to control the screen
	 */
	PowerManager.WakeLock wakeLock;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle bdl) {
		super.onCreate(bdl);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.record_menu);
		handler = new Handler();
		list = (ListView) findViewById(R.id.gridView);
		list.setEmptyView(findViewById(R.id.empty));
		stateButton = (Button) this.findViewById(R.id.recordStateButton);

		// 如果还没有登录微博，则提示登录微博
		// if (IMDroid.getWeiboLoginRemind() && Weibo.toAuth) {
		// Weibo.quickAuth(this);
		// Weibo.toAuth = false;
		// }
		// 启动线程
		timeRunner = new TimeRunner(60 * 1000, 1 * 1000);
		timeRunner.start();

//		GridView gv = (GridView) this.findViewById(R.id.gridView);

		list.setOnTouchListener(new View.OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				Log.d(TAG, "ON CLICK");
				if (timeRunner != null) {
					timeRunner.cancel();
					stateButton.setText("");
				}
				return false;
			}
		});
		
		// 按任意Item停止计时
//		gv.setOnTouchListener(new View.OnTouchListener() {
//			public boolean onTouch(View v, MotionEvent event) {
//				Log.d(TAG, "ON CLICK");
//				if (timeRunner != null) {
//					timeRunner.cancel();
//					stateButton.setText("");
//				}
//				return false;
//			}
//		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onDestroy()
	 */
	public void onDestroy() {
		super.onDestroy();
		if (sa != null) {
			sa.stop();
			sa = null;
		}
		if (timeRunner != null)
			timeRunner.cancel();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStart()
	 */
	public void onStart() {
		super.onStart();
		// 设置不锁屏，得到wake log
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, this
				.getClass().getCanonicalName());
		wakeLock.acquire();

		// 如果正在录像，则进入录像界面
		if (Record.needRecord) {
			record(this.findViewById(R.id.recordTtlButton));
			this.finish();
		}
		if (sa == null) {
			checkCache();
		}
		// ttl = 6;
		// timer();//非第一次进来，不用自动录像。
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStop()
	 */
	protected void onStop() {
		if (wakeLock != null)
			wakeLock.release();
		super.onStop();
	}

	/**
	 * 启动录像记录行车状态
	 * 
	 * @param view
	 */
	public void record(View view) {
		if (sa != null) {
			sa.stop();
			sa = null;
		}
		startActivity(new Intent(this, RecordActivity.class));
		finish();
	}

	/**
	 * 点击播放视频文件
	 * 
	 * @param view
	 *            the video file
	 */
	public void play(View view) {
		if (timeRunner != null) {
			timeRunner.cancel();
			stateButton.setText("");
		}
		if (view.getTag() instanceof File) {
			Intent in = new Intent(Intent.ACTION_VIEW);
			in.putExtra("oneshot", 0);
			in.putExtra("configchange", 0);
			in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			in.setDataAndType(Uri.fromFile((File) view.getTag()), "video/*");
			startActivity(in);
		}
	}

	/**
	 * 返回上一界面
	 * 
	 * @param view
	 */
	public void back(View view) {
		finish();
	}

	/**
	 * 检查缓存 -每个视频生成缩略图
	 */
	private void checkCache() {
		// findViewById(R.id.loading).setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				// 检查cache目录，有多余的删除
//				File root = new File(IMDroid.VIDEO_SCREEN_CACHE);
//				if (!root.exists())
//					root.mkdirs();
//				File[] caches = root.listFiles();
//				for (File cache : caches) {
//					String name = cache.getAbsolutePath();
//					name = name.substring(0, name.length() - 6).replace(
//							IMDroid.VIDEO_SCREEN_CACHE, IMDroid.VIDEO_FOLDER);
//					if (!((new File(name)).exists())) {
//						cache.delete();
//					}
//				}
//				// 遍历video目录，没有生成缩略图的重新生成
//				File[] videos = new File(IMDroid.VIDEO_FOLDER).listFiles();
//				for (File video : videos) {
					// 如果文件大小的，则认为是有问题文件，则删除
					// if (video.length() < 102400) {
					// video.delete();
					// continue;
					// }
//					String name = video.getAbsolutePath();
//					name = name.replace(IMDroid.VIDEO_FOLDER,
//							IMDroid.VIDEO_SCREEN_CACHE) + ".cache";
//					if (!((new File(name)).exists())) {
//						try {
//							// 获取缩略图
//							Bitmap bmp = capture(video);
//							if (bmp != null) {
//								OutputStream os = new FileOutputStream(name);
//								bmp = Bitmap.createScaledBitmap(bmp, 160, 120,
//										false);
//								// 压缩图片
//								bmp.compress(CompressFormat.JPEG, 50, os);
//								os.close();
//							}
//						} catch (Exception e) {
//							e.printStackTrace();
//						}
//					}
//				}
				if (handler != null) {
					handler.post(new Runnable() {
						public void run() {
							loadHistory();
						}
					});
				}
			}
		}.start();
	}

	// 加载历史列表
	private void loadHistory() {
		// 遍历video目录
		File file = new File(IMDroid.VIDEO_FOLDER);
		File[] files = file.listFiles(videoFileFilter);
		if (files == null || files.length == 0) {
			// 如果没有录像文件，则显示“当前无记录”
			// findViewById(R.id.empty).setVisibility(View.VISIBLE);
			return;
		}
		Arrays.sort(files, fileComparator);
		if (data != null)
			data.clear();
		data = new ArrayList<HashMap<String, Object>>();
		for (File f : files) {
			HashMap<String, Object> item = new HashMap<String, Object>();
			item.put("file", f);
			String size = (f.length()/1024/1024)+"";
			if(size.contains(".")){
				int end = size.indexOf('.') + 3;
				if(end > size.length())
					end = size.length();
				size = size.substring(0, end);
			}
			
			item.put("size", size + " MB");
			item.put("name", f.getAbsolutePath().replace(IMDroid.VIDEO_FOLDER, ""));
//			item.put(
//					"cache",
//					f.getAbsolutePath().replace(IMDroid.VIDEO_FOLDER,
//							IMDroid.VIDEO_SCREEN_CACHE)
//							+ ".cache");
			data.add(item);
		}
		
		SimpleAdapter sa = new SimpleAdapter(this, data, R.layout.video_list, new String[]{"name", "size"}, new int[]{R.id.name, R.id.size});
		list.setAdapter(sa);
		list.setOnItemClickListener(new OnItemClickListener(){

			/* (non-Javadoc)
			 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
			 */
			@Override
			public void onItemClick(AdapterView<?> l, View view, int pos,
					long id) {
				Map<String, Object> item = (Map<String, Object>)list.getItemAtPosition(pos);
				if (timeRunner != null) {
					timeRunner.cancel();
					stateButton.setText("");
				}
				Intent in = new Intent(Intent.ACTION_VIEW);
				in.putExtra("oneshot", 0);
				in.putExtra("configchange", 0);
				in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				in.setDataAndType(Uri.fromFile((File) item.get("file")), "video/*");
				startActivity(in);
			}
			
		});
//		sa = new VideoAdapter(this, list, data, R.layout.record_image_item,
//				new String[] {}, new int[] {});
//		sa.start();
//		list.setAdapter(sa);
		// findViewById(R.id.empty).setVisibility(View.GONE);
		// findViewById(R.id.loading).setVisibility(View.GONE);
	}

	/**
	 * 获取缩略图
	 * 
	 * @param file
	 *            the video file
	 * @return the bitmap byte of picture
	 * @throws IOException
	 */
	@SuppressLint("NewApi")
	private Bitmap capture(File file) throws IOException {
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		FileInputStream fis = new FileInputStream(file);
		retriever.setDataSource(fis.getFD());
		// 第一秒
		Bitmap bmp = retriever.getFrameAtTime(1000000,
				MediaMetadataRetriever.OPTION_CLOSEST);
		retriever.release();
		fis.close();
		return bmp;
	}

	// / 过滤器，只接受大于100K的视频文件
	private static FileFilter videoFileFilter = new FileFilter() {
		public boolean accept(File file) {
			String name = file.getName();
			if (name.endsWith(".3gp") && file.length() >= 1024 )
				return true;
			return false;
		}
	};

	// 按文件最后修改时间降序排序的比较器
	private static Comparator<File> fileComparator = new Comparator<File>() {
		public int compare(File lhs, File rhs) {
			return (int) (rhs.lastModified() - lhs.lastModified());
		}
	};

	/**
	 * The time runner
	 */
	private class TimeRunner extends CountDownTimer {
		String text = RecordMenuActivity.this.getString(R.string.video_start);

		/**
		 * The constructor of time runner
		 * 
		 * @param millisInFuture
		 * @param countDownInterval
		 */
		public TimeRunner(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.CountDownTimer#onFinish()
		 */
		public void onFinish() {
			Button button = (Button) RecordMenuActivity.this
					.findViewById(R.id.recordTtlButton);
			record(button);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.CountDownTimer#onTick(long)
		 */
		@SuppressLint("SimpleDateFormat")
		public void onTick(long millisUntilFinished) {
			SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
			stateButton.setText(text.replace("%1%",
					sdf.format(new Date(millisUntilFinished))));

		}

	}

	// 视频列表适配器
	private class VideoAdapter extends SimpleAdapter {
		private ArrayList<HashMap<String, Object>> data;
		private GridView grid;
		private volatile boolean running = true;
		private Thread loadThread;
		private Handler handler;

		private HashMap<String, SoftReference<Bitmap>> cache = new HashMap<String, SoftReference<Bitmap>>();
		private HashMap<String, File> files = new HashMap<String, File>();
		private LinkedList<String> images = new LinkedList<String>();

		/**
		 * @param context
		 * @param grid
		 * @param data
		 * @param resource
		 * @param from
		 * @param to
		 */
		public VideoAdapter(Context context, GridView grid,
				ArrayList<HashMap<String, Object>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.data = data;
			this.grid = grid;
			handler = new Handler();
		}

		public void start() {
			if (loadThread != null)
				stop();
			running = true;
			// Collections.sort(images, new ViedioFileComparator());
			loadThread = new Thread(loader);
			loadThread.start();
		}

		public void stop() {
			running = false;
			files.clear();
			if (loadThread != null) {
				synchronized (images) {
					images.notify();
				}
				loadThread = null;
			}
		}

		private Bitmap getBitmap(String name, File video) {
			Bitmap bmp = null;
			SoftReference<Bitmap> sr = cache.get(name);
			if (sr != null)
				bmp = sr.get();
			if (bmp != null) {
				return bmp;
			}

			synchronized (images) {
				files.put(name, video);
				images.add(name);
				images.notify();
			}

			// bmp = BitmapFactory.decodeFile(name);
			// cache.put(name, new SoftReference<Bitmap>(bmp));
			return bmp;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.widget.SimpleAdapter#getView(int, android.view.View,
		 * android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			VH vh = null;
			if (convertView == null) {
				convertView = super.getView(position, convertView, parent);
				vh = new VH();
				vh.image = (ImageView) convertView.findViewById(R.id.image);
				vh.textView = (TextView) convertView
						.findViewById(R.id.record_image_tv);
				convertView.setTag(vh);
			} else {
				vh = (VH) convertView.getTag();
			}

			HashMap<String, Object> item = data.get(position);
			convertView.findViewById(R.id.play).setTag(item.get("file"));
			vh.image.setImageBitmap(null);
			vh.image.setTag(item.get("cache"));
			Bitmap bmp = getBitmap((String) item.get("cache"),
					(File) item.get("file"));
			if (bmp != null) {
				vh.image.setImageBitmap(bmp);
			}

			return convertView;
		}

		private Runnable loader = new Runnable() {
			public void run() {
				outer: while (true) {
					String file = null;
					synchronized (images) {
						while (images.size() == 0) {
							try {
								images.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							if (!running)
								break outer;
						}
						file = images.removeFirst();
					}
					// if(files.get(file) != null &&
					// grid.findViewWithTag(files.get(file)) == null)
					// continue;

					final Bitmap bmp = BitmapFactory.decodeFile(file);
					cache.put(file, new SoftReference<Bitmap>(bmp));
					if (loadThread == null)
						break;
					if (loadThread.getName().equals(
							Thread.currentThread().getName())) {
						final String FILE = file;
						handler.post(new Runnable() {
							public void run() {
								try {
									FrameLayout frame = (FrameLayout) (grid
											.findViewWithTag(files.get(FILE))
											.getParent());

									ImageView iv = (ImageView) (frame
											.findViewById(R.id.image));

									TextView tv = (TextView) (frame
											.findViewById(R.id.record_image_tv));
									Log.d("TAG", "file---" + FILE);
									if (iv != null)
										iv.setImageBitmap(bmp);

									if (tv != null)
										tv.setText(getTime(FILE));
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						});
					} else {
						break;
					}
				}

			}
		};

		/**
		 * Get the date time format from the video file name
		 * 
		 * @param file
		 *            the file name
		 * @return the date time format
		 */
		@SuppressWarnings("deprecation")
		@SuppressLint("SimpleDateFormat")
		private String getTime(String file) {
			Log.d(TAG, "==" + file);
			SimpleDateFormat formatDate = new SimpleDateFormat(
					"yyyy-MM-dd-HH-mm-ss");
			SimpleDateFormat targetFormat1 = new SimpleDateFormat("HH:mm:ss");
			SimpleDateFormat targetFormat2 = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");

			// Sample -
			// /storage/emulated/0/IMDroid/vcache/2013-05-23-13-42-09_113.353453-23.135103-0.000000.3gp.cache
			String[] item = file.split("/");
			if (item == null || item.length <= 0) {
				return "";
			}
			String temp = item[item.length - 1];
			if (temp != null && temp.length() <= 0)
				return "";

			String[] str = temp.split("_");
			if (str == null || str.length <= 0) {
				return "";
			}

			try {
				Date vedioDate = formatDate.parse(str[0]);
				Date today = new Date();
				if (vedioDate.getYear() == today.getYear()
						&& vedioDate.getMonth() == today.getMonth()
						&& vedioDate.getDate() == today.getDate())
					return targetFormat1.format(vedioDate);
				else
					return targetFormat2.format(vedioDate);

			} catch (ParseException e) {
				return "";
			}
		}

		private class VH {
			private ImageView image;
			@SuppressWarnings("unused")
			private TextView textView;
		}
	}

}
